/*
Copyright © 2022 NAME HERE <EMAIL ADDRESS>
*/
package cmd

import (
	"fmt"

	"strconv"
	"strings"

	devices "gitee.com/zinface/gpio-ctl/pkg/gpio"
	"github.com/spf13/cobra"
)

// setmodeCmd represents the setmode command
var setmodeCmd = &cobra.Command{
	Use:   "setmode",
	Short: _desc_setmode_,
	Long:  ``,
	Run: func(cmd *cobra.Command, args []string) {
		if len(args) > 1 {
			var err error

			// 获取第一个参数
			id, err := strconv.Atoi(args[0])
			if err != nil {
				panic(err)
			}

			// 获取第二个参数
			var value int
			if strings.Contains(args[1], "in") {
				value = int(devices.DIRECTION_IN)
			} else if strings.Contains(args[1], "out") {
				value = int(devices.DIRECTION_OUT)
			} else {
				value, err = strconv.Atoi(args[1])
				if err != nil {
					panic(err)
				}
			}

			var modevalue string
			if value == 0 {
				modevalue = "in"
			} else {
				modevalue = "out"
			}

			// 尝试写入已导出设备的值
			gpio := devices.NewGPIODevice(id)
			if gpio.IsExported() {
				var mode devices.GPIOMode = devices.DIRECTION_IN
				if value == 0 {
					mode = devices.DIRECTION_IN
				} else {
					mode = devices.DIRECTION_OUT
				}
				gpio.ChangeMode(mode)

				fmt.Printf("SetMode: gpio%d direction %s success.\n", id, modevalue)
			}
		}
	},
}

func init() {
	rootCmd.AddCommand(setmodeCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// setmodeCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// setmodeCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
